package com.example.administrator.shzs.fragment.order;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.administrator.shzs.R;
import com.example.administrator.shzs.fragment.UserFragment;
import com.example.administrator.shzs.activity.LogInActivity;
import com.example.administrator.shzs.adapter.AllOrderAdapter;
import com.example.administrator.shzs.app.MyApplication;
import com.example.administrator.shzs.url.Contents;
import com.example.administrator.shzs.entity.OrderAll;
import com.example.administrator.shzs.ui.OrderdetailActivity;
import com.jcodecraeer.xrecyclerview.ProgressStyle;
import com.jcodecraeer.xrecyclerview.XRecyclerView;

import java.io.IOException;
import java.util.HashSet;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 全部订单
 */
public class AllOrderFragment extends Fragment implements AllOrderAdapter.OrdelAlll {

    @Bind(R.id.tv_delete)
    TextView tvDelete;
    @Bind(R.id.tv_select_all)
    TextView tvSelectAll;
    @Bind(R.id.lly_menu)
    LinearLayout llyMenu;
    @Bind(R.id.Mes)
    RelativeLayout Mes;
    @Bind(R.id.imageloding)
    ImageView imageloding;
    @Bind(R.id.progressbar)
    ProgressBar progressbar;
    @Bind(R.id.AllOrder)
    TextView AllOrder;
    @Bind(R.id.order_login)
    LinearLayout orderLogin;


    private XRecyclerView mXrecyclerView;

    private AllOrderAdapter adapter;

    private List<OrderAll> datalist;
    private List<OrderAll> templist;

    private int page = 1;

    //记录Menu的状态
    private boolean isShow;
    private boolean isSelectAll;
    private HashSet<Integer> postionSet;


    private MyBrodcastReceiver myBrodcastReceiver;

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_all_order, null);
        //初始化
        setViews(view);
        //获取网络数据
        setData();

        mXrecyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                page = 1;
                setData();
            }

            @Override
            public void onLoadMore() {
                page++;
                setData();
            }
        });

        ButterKnife.bind(this, view);
        return view;
    }


    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    //如何有数据则显示
                    if (datalist.size() > 0) {
                        //登录提示 隐藏
                        orderLogin.setVisibility(View.GONE);
                        //列表 隐藏
                        mXrecyclerView.setVisibility(View.VISIBLE);
                    } else {
//                        如果没有数据就显示
                        mXrecyclerView.setVisibility(View.GONE);

                            //如何没有数据进行判断 用户 uid是否存在  ，等于null
                        if (MyApplication.app.getUserId() == null) {
                            //登录提示 显示
                            mXrecyclerView.setVisibility(View.GONE);
                            orderLogin.setVisibility(View.VISIBLE);
                            orderLogin.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    Intent intent = new Intent(getActivity(), LogInActivity.class);
                                    startActivity(intent);
                                }
                            });
                        }else {
                            //如果id存在就显示
                            mXrecyclerView.setVisibility(View.VISIBLE);
                        }

                    }
                    mXrecyclerView.loadMoreComplete();
                    mXrecyclerView.refreshComplete();
                    break;
                case 1:
                    //等待中
                    progressbar.setVisibility(View.GONE);
                    orderLogin.setVisibility(View.GONE);
                    mXrecyclerView.setVisibility(View.VISIBLE);

                    adapter = new AllOrderAdapter(datalist, getActivity());
                    mXrecyclerView.setAdapter(adapter);
                    mXrecyclerView.refreshComplete();
                    adapter.setOrdelAlll(AllOrderFragment.this);

                    break;
                case 2:
                    datalist.addAll(templist);
                    adapter.notifyDataSetChanged();
                    templist.clear();
                    mXrecyclerView.loadMoreComplete();

                    break;
            }
        }
    };


    @Override
    public void Onclick(View view, int postion, int po, String shopImage) {
        if (po == 0) {
//            Toast.makeText(getActivity(), "再来一单", Toast.LENGTH_SHORT).show();
        } else if (po == 1) {
            Intent intent = new Intent(getActivity(), OrderdetailActivity.class);
            intent.putExtra("orderId", datalist.get(postion).getOrderID());
            //订单状态
            intent.putExtra("State", datalist.get(postion).getState());
            intent.putExtra("shopImage", shopImage);

            startActivity(intent);

        }
    }


    /**
     *
     */

    public void setData() {

        postionSet = new HashSet<>();

//        progressbar.setVisibility(View.VISIBLE);

        String url = Contents.ORDER_ALL + MyApplication.app.getUserId() + "&pagesize=20&pageindex=" + page;
        Request request = new Request.Builder().url(url).build();

        Log.i("orderAllrequest", request + "");
        Contents.okhttp.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                handler.sendEmptyMessage(0);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String request = response.body().string();
                if (page == 1) {
                    datalist = UserFragment.OrdelAllUtils.getOrderAll(request);
                    if (datalist.size() > 0) {
                        handler.sendEmptyMessage(1);
                    } else {
                        handler.sendEmptyMessage(0);
                    }
                } else {
                    templist = UserFragment.OrdelAllUtils.getOrderAll(request);
                    if (templist.size() > 0) {
                        handler.sendEmptyMessage(2);
                    } else {
                        handler.sendEmptyMessage(0);
                    }
                }
            }
        });
    }

    //接收广播进行执行操作
    class MyBrodcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            setData();
        }
    }

    /**
     * 初始化
     *
     * @param view
     */
    public void setViews(View view) {
        //注册广播
        myBrodcastReceiver = new MyBrodcastReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("1");
        getActivity().registerReceiver(myBrodcastReceiver, intentFilter);


        mXrecyclerView = (XRecyclerView) view.findViewById(R.id.mXrecyclerView_all_order);
//        布局管理器
        LinearLayoutManager manager = new LinearLayoutManager(getActivity());
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        mXrecyclerView.setLayoutManager(manager);
        mXrecyclerView.setRefreshing(true);

        mXrecyclerView.setRefreshProgressStyle(ProgressStyle.BallSpinFadeLoader);
        mXrecyclerView.setLoadingMoreProgressStyle(ProgressStyle.SquareSpin);

    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }


}
